import os
import sys
import pyautogui as auto
import time
import configparser
from PIL import Image
import cv2

'''属性设置'''
config = configparser.ConfigParser()
config.read('config.ini', encoding='utf-8')
Apath = config.get('main', 'Apath')
pausetime = config.getint('main', 'PauseTime')
ip = config.get('main', 'IP')
c = config.get('main', 'Confidence')
SC = config.getboolean('main', 'StoneCrush')

filename = 'screenshot.png'

def screenshot():
    os.system(f"adb shell screencap -p {Apath}/{filename}")
    os.system(f"adb pull /sdcard/{filename}")

def getResolution():
    screenshot()
    try:
        global SR # ScreenResolution
        img = Image.open(filename)
        SR = f'{img.size[0]}x{img.size[1]}'
        return SR
    except:
        print('ADB连接失败，请打开模拟器后重试')
        sys.exit(0)

def tap(x:int or tuple, y=None):
    if y is None:
        x, y = x
    # print(f'点击坐标 {x} {y}')
    os.system(f'adb shell input tap {x} {y}')

def locatePic(pic:str, msg=None, loop=False, pause=pausetime, click=True):
    p = None
    while True:
        p = auto.locate(f'./picture/{SR}/{pic}', filename, confidence=0.8)
        if p:
            if msg: print(msg)
            if click: 
                tap(auto.center(p))
                time.sleep(pause)
            break
        if not loop:
            break
    return p

def battle(times:int):
    extra = os.path.exists(f'./picture/{SR}/extra')
    i = 0
    while i < times:
        screenshot()
        if locatePic('0-dlzh.png', '开启代理指挥'):
            pass
        elif locatePic('1-os1.png', '开始行动1'):
            pass
        elif locatePic('2-lzbz.png', click=False):
            if SC:
                locatePic('2-lzbz.png', '理智不足，碎石', click=True)
            else:
                print('理智不足，脚本终止')
                break
        elif locatePic('2-os2.png', '开始行动2'):
            print(f'--------第{i+1}次战斗开始--------')
            time.sleep(5)
        elif locatePic('3-battling.png', click=False):
            print('战斗中')
            while locatePic('3-battling.png', click=False):
                time.sleep(6)
                screenshot()
            print('战斗结算')
        elif locatePic('4-victory.png', f'--------第{i+1}次战斗胜利--------'):
            i += 1
        if extra:
            if locatePic('extra/4-defeat.png', click=False):
                print('--------战斗失败，脚本终止--------')
                tap(100, 100)
                break
            if locatePic('extra/5-jm.png', f'--------第{i+1}次战斗胜利--------'):
                i += 1
                while True:
                    p = locatePic('extra/5-jm2.png', click=False)
                    if p:
                        tap(100, 100)
                        break
                    time.sleep(1)
                    screenshot()
        else:
            time.sleep(1)

print("欢迎使用明日方舟自动挂机程序")
print("--------初始化中--------")
os.system(f'adb connect {ip}')
getResolution()
print(f'模拟器当前分辨率：{SR}')
print(f'点击间隔：{pausetime}')
print(f'图片识别率:{c}')
print(f'碎石模式：{SC}')
if not os.path.exists(f'./picture/{SR}'):
    print('错误！当前分辨率暂不支持。')
    os.system('pause')
    os.system(f'adb disconnect {ip}')
    exit(0)
print("--------初始化完成--------")

while True:
    try:
        times = input("请输入次数(或q退出)：")
        if times == 'q':
            break
        else:
            battle(int(times))
    except ValueError as e:
        print('非法输入')
    except Exception as e:
        print(e)

os.system(f'adb disconnect {ip}')